package http_service

import (
	"context"
	"geektime-cn/http_service/middlewares"
	"net/http"
)

type Router struct {
	Pattern string
	Handler http.HandlerFunc
}

type httpSrv struct {
	mux     *http.ServeMux
	server  *http.Server
	middles []middlewares.Middleware
}

func NewHttpSrv(routers ...Router) *httpSrv {
	srv := &httpSrv{
		mux:     http.NewServeMux(),
		middles: make([]middlewares.Middleware, 0),
	}
	srv.Use(middlewares.WithLog, middlewares.WithEnvVersion, middlewares.WithCloneReqHeaders)

	for _, router := range routers {
		srv.HandleFunc(router.Pattern, router.Handler)
	}

	return srv
}

func (s *httpSrv) Use(middlewares ...middlewares.Middleware) {
	for _, middleware := range middlewares {
		s.middles = append(s.middles, middleware)
	}
}

func (s *httpSrv) HandleFunc(pattern string, handler http.HandlerFunc) {
	var newHandler http.Handler
	newHandler = handler
	if s.middles != nil {
		for _, middle := range s.middles {
			newHandler = middle(newHandler)
		}
	}
	s.mux.Handle(pattern, newHandler)
}

func (s *httpSrv) ListenAndServe(addr string) error {
	s.server = &http.Server{
		Addr:    addr,
		Handler: s.mux,
	}

	return s.server.ListenAndServe()
}

func (s *httpSrv) Shutdown(ctx context.Context) error {
	return s.server.Shutdown(ctx)
}
